package nz.co.listit.TaxiValet;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;

public class CustomExceptionHandler implements UncaughtExceptionHandler {

	private UncaughtExceptionHandler _defaultExceptionHandler;
	private Context _context;

	// constructor
	public CustomExceptionHandler(Context context) {
		_defaultExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
		_context = context;
	}

	public void uncaughtException(Thread thread, Throwable ex) {
		final Writer writer = new StringWriter();
		final PrintWriter printWriter = new PrintWriter(writer);

		ex.printStackTrace(printWriter);
		String stackTrace = writer.toString();

		// send error to server
		ListItResClient client = (ListItResClient) _context;
		ListItServerClient ltClient = new ListItServerClient();

		List<NameValuePair> qparams = new ArrayList<NameValuePair>();

		// add device ID
		qparams.add(new BasicNameValuePair("deviceID", client.getDeviceID()));
		qparams.add(new BasicNameValuePair("stackTrace", stackTrace));

		// call web service
		ltClient.queryListItService("ReportUnhandledError", qparams);

		printWriter.close();

		_defaultExceptionHandler.uncaughtException(thread, ex);
	}

}
